package com.edu.framework.websocket.handler;

import cn.hutool.core.util.StrUtil;
import com.edu.framework.websocket.WebSocketHolder;
import com.edu.framework.websocket.message.base.Response;
import com.edu.framework.websocket.message.examseat.ExamSeatEditRequest;
import com.edu.framework.websocket.message.examseat.ExamSeatRequest;
import com.edu.framework.websocket.message.examseat.ExamSeatVO;
import com.edu.framework.websocket.service.ExamSeatService;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

@Component
public class ExamSeatEditRequestHandler implements IHandler<ExamSeatEditRequest> {

    @Resource
    private ExamSeatService wsExamSeatService;

    @Override
    public void execute(WebSocketSession session, ExamSeatEditRequest message) {
        if (message == null) {
            return;
        }
        Map<String, String> data = message.getData();
        String examSeatId = data.get(ExamSeatEditRequest.EXAM_SEAT_ID_KEY);
        String missIds = data.get(ExamSeatEditRequest.MISS_NAME_IDS_KEY);
        String cardNo = data.get(ExamSeatEditRequest.TEACHER_CARD_ID);
        String password = data.get(ExamSeatEditRequest.PASSWORD);
        Response<Integer> response = null;

        // 权限校验
        String checkRes = wsExamSeatService.checkValid(cardNo, password);

        if (examSeatId == null){
            response = Response.fail(ExamSeatEditRequest.TYPE, "座位图id不能为空");
        }
        else if (StrUtil.isNotBlank(checkRes)){
            response = Response.fail(ExamSeatEditRequest.TYPE, checkRes);
        }
        else if (StrUtil.isBlank(missIds)){
            response = Response.ok(ExamSeatEditRequest.TYPE, ExamSeatEditRequest.RESP_KEY, 0);
        }
        else {
            int i = wsExamSeatService.editMissExam(
                Long.parseLong(examSeatId),
                Stream.of(missIds.split(",")).map(Long::parseLong).collect(Collectors.toList()
                )
            );
            response = Response.ok(ExamSeatEditRequest.TYPE, ExamSeatEditRequest.RESP_KEY, i);
        }

        try {
            WebSocketHolder.send(session,response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public String getType() {
        return ExamSeatEditRequest.TYPE;
    }
}
